package com.TinyBBS.servlet;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.TinyBBS.bean.User;
import com.TinyBBS.model.UserModel;

/**
 * Servlet implementation class Profile
 */
public class Profile extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession(true);
		String username = (String) session.getAttribute("username");
		String error = "";
		String uri = "";
		if(username == null){
			uri = "views/login.jsp";
		}else{
			UserModel userM = new UserModel();
			if(request.getParameter("profilesubmit") != null){
				// deal with update profile
				String firstname = request.getParameter("firstname");
				String lastname = request.getParameter("lastname");
				String email = request.getParameter("email");
				Map<String,Object> map = new HashMap<String,Object>();
				map.put("firstname", firstname);
				map.put("lastname", lastname);
				if(userM.updateData(map, username)){
					User user = userM.getUserByUsername(username);
					request.setAttribute("username", user.getUsername());
					request.setAttribute("firstname", user.getFirstname());
					request.setAttribute("lastname",user.getLastname() );
					request.setAttribute("email", user.getEmail());
					uri = "views/profile.jsp";
					error = "Updated successfully";
				}else{
					error = "Failed to update data";
					uri = "views/profile.jsp";
				}
				
			}else{
				
				User user = userM.getUserByUsername(username);
				request.setAttribute("username", user.getUsername());
				request.setAttribute("firstname", user.getFirstname());
				request.setAttribute("lastname",user.getLastname() );
				request.setAttribute("email", user.getEmail());
				uri = "views/profile.jsp";
			}
		}
		request.setAttribute("error", error);
		System.out.println();
		RequestDispatcher rd = request.getRequestDispatcher(uri);
		rd.forward(request, response);
	}
}
